package socketwork1;

import jdk.internal.util.xml.impl.Input;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server {
    private ServerSocket serverSocket;// 总机

    private List<PrintWriter> allOut = new ArrayList<>();// 设计集合存放所有客户端输出流, 用于群发

    public Server(){
        try {
            System.out.println("正在启动服务器");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            System.out.println("等待客户连接...");
            Socket socket = serverSocket.accept();
            System.out.println("一个客户连接了!");

            ClientHandler handler = new ClientHandler(socket);
            Thread t = new Thread(handler);
            t.start();
        } catch (IOException e) {
            //e.printStackTrace(); //冷处理
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket){this.socket = socket;}

        public void run(){
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter ows = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(ows);
                PrintWriter pw = new PrintWriter(bw,true);

                allOut.add(pw);

                String message;
                while((message=br.readLine())!=null){
                    sendMessageToAll("客户端说: "+message);
                }
            } catch (IOException e) {
            }finally {
                try {
                    socket.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        private void sendMessageToAll(String message){
            System.out.println(message);
            for(PrintWriter o :allOut){
                o .println(message);
            }
        }
    }
}
